<template>
  <div class="container" :style="{ backgroundImage: bg }">
    <!--对话框 start-->
    <div>
      <!--添加-->
      <el-dialog
          draggable
          destroy-on-close
          v-model="dialogAddVisible"
          title="添加"
          width="70%"
          center>
        <el-form inline :model="addFormInfo" label-width="150px">
          <el-form-item label="标题">
            <el-input v-model="addFormInfo.announcementTitle"></el-input>
          </el-form-item>
          <el-form-item label="简介">
            <el-input type="textarea" rows="3" style="width: 800px" v-model="addFormInfo.announcementDesc"></el-input>
          </el-form-item>
          <el-form-item label="内容">
            <el-input type="textarea" rows="10" style="width: 800px"
                      v-model="addFormInfo.announcementContent"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogAddVisible = false">取消</el-button>
                <el-button type="primary" @click="sureHandler">确定</el-button>
            </span>
        </template>
      </el-dialog>
      <!--编辑-->
      <el-dialog
          draggable
          destroy-on-close
          v-model="dialogEditorVisible"
          title="编辑"
          width="70%"
          center>
        <el-form inline :model="editorFormInfo" label-width="150px">
          <el-form-item label="标题">
            <el-input v-model="editorFormInfo.announcementTitle"></el-input>
          </el-form-item>
          <el-form-item label="简介">
            <el-input type="textarea" rows="3" style="width: 800px"
                      v-model="editorFormInfo.announcementDesc"></el-input>
          </el-form-item>
          <el-form-item label="内容">
            <el-input type="textarea" rows="10" style="width: 800px"
                      v-model="editorFormInfo.announcementContent"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogEditorVisible = false">取消</el-button>
                <el-button type="primary" @click="sureEditorHandler">确定</el-button>
            </span>
        </template>
      </el-dialog>
    </div>
    <!--对话框 end-->

    <!--顶部 start-->
    <div class="header" v-if="headerShow">
      <div class="search">
        <el-input class="input" size="large" @keyup.enter="searchHandle" v-model="searchInfo"
                  placeholder="请输入关键字"></el-input>
        <el-button icon="Search" size="large" @click="searchHandle" color="#3c8dbc">搜索</el-button>
      </div>
    </div>
    <!--顶部 end-->

    <!--表格 start-->
    <div class="table-container">
      <div class="table-header">
        <div class="button-list">
          <el-button class="button" icon="DocumentAdd" type="success" @click="addHander">新增</el-button>
          <el-upload
              :show-file-list="false"
              :action="dataStore.fastdfsUploadUrl"
              :on-success="onUploadSuccess"
          >
            <el-button class="button" icon="Document" type="primary">导入</el-button>
          </el-upload>
          <el-button class="button" @click="exportHandle" icon="DocumentAdd" type="warning">导出</el-button>
        </div>
        <div class="icon-list">
          <el-button icon="search" color="#3c8dbc" @click="headerShow?headerShow=false:headerShow=true"></el-button>
          <el-button icon="RefreshRight" color="#269846" @click="reload"></el-button>
          <el-button icon="ArrowLeftBold" color="#133c9a" @click="onClickLeft"></el-button>
        </div>
      </div>
      <el-table class="table" :data="dataList.list" highlight-current-row height="400">
        <el-table-column show-overflow-tooltip label="标题" prop="announcementTitle" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip label="简介" prop="announcementDesc" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip label="内容" prop="announcementContent" align="center"></el-table-column>
        <el-table-column label="发布时间" prop="announcementTime" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button size="small" icon="edit" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button size="small" icon="delete" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          layout="prev,pager,next,jumper"
          :default-page-size="defaultPageSize"
          :total="totalData"
          @current-change="currentChangeHaddler"></el-pagination>
    </div>
    <!--表格 end-->

    <!--底部 start-->
    <div class="bottom">
      <span>© 2024 YueMu Copyrigh</span>
    </div>
    <!--底部 end-->
  </div>
</template>

<script setup>
import websiteAxios from "@/api/website.js"
import {onMounted, reactive, ref} from "vue";
import {useDataStore} from "@/stores/dataStore.js"
import axios from "@/api/request"

const dataStore = useDataStore()
//顶部显示
const headerShow = ref(true)
/**
 * 返回
 */
const onClickLeft = () => {
  history.back();
}
/**
 * 刷新页面
 */
const reload = () => {
  location.reload();
}
//初始化分页查询数据
const dataList = reactive({
  list: []
})
//初始化总条数
const totalData = ref(0)
//当前页
const currentPage = ref(1)
//初始化分页显示条数
const defaultPageSize = ref(10)
//搜索初始化状态
const searchInfo = ref("")
//添加添加对话框控制器
const dialogAddVisible = ref(false)
//初始化添加对话框状态
const addFormInfo = reactive({
  announcementTitle: "",
  announcementDesc: "",
  announcementContent: "",
  announcementTime: "",
})
//编辑对话框控制器
const dialogEditorVisible = ref(false)
//初始化编辑对话框状态
const editorFormInfo = reactive({
  announcementId: '',
  announcementTitle: "",
  announcementDesc: "",
  announcementContent: "",
  announcementTime: "",
})
/**
 * 网路请求
 */
//分页查询
const http = () => {
  websiteAxios.announcement_search({
    search: searchInfo.value,
    page: currentPage.value,
    size: defaultPageSize.value
  }).then(res => {
    if (res.data.code == 200) {
      dataList.list = res.data.data.records
      totalData.value = res.data.data.total
    } else {
      ElMessage.error(res.data.message)
    }
  })
}
onMounted(() => {
  http()
})
//分页
const currentChangeHaddler = (nowPage) => {
  currentPage.value = nowPage
  http()
}
//搜索
const searchHandle = () => {
  http()
}
/**
 * 添加对话框弹出事件
 */
const addHander = () => {
  dialogAddVisible.value = true
}
/**
 * 添加对话框 确定事件
 */
const sureHandler = () => {
  //获取当前时间
  let date = new Date();
  let year = date.getFullYear();
  let month = (date.getMonth() + 1).toString().padStart(2, '0');
  let day = date.getDate().toString().padStart(2, '0');
  //格式为  x年x月x日
  let formattedDate = `${year}年${month}月${day}日`;
  websiteAxios.announcement_add({
    announcementTitle: addFormInfo.announcementTitle,
    announcementDesc: addFormInfo.announcementDesc,
    announcementContent: addFormInfo.announcementContent,
    announcementTime: formattedDate,
  }).then(res => {
    if (res.data.code == 200) {
      dialogAddVisible.value = false
      http()
    } else {
      ElMessage.error(res.data.message)
    }
  })
}
/**
 * 编辑对话框 弹出事件
 *  */
const handleEdit = (index, row) => {
  dialogEditorVisible.value = true
  websiteAxios.announcement_findById({
    announcementId: row.announcementId
  }).then(res => {
    if (res.data.code == 200) {
      editorFormInfo.announcementId = res.data.data.announcementId;
      editorFormInfo.announcementTitle = res.data.data.announcementTitle;
      editorFormInfo.announcementDesc = res.data.data.announcementDesc;
      editorFormInfo.announcementContent = res.data.data.announcementContent;
      editorFormInfo.announcementTime = res.data.data.announcementTime;
    } else {
      ElMessage.error(res.data.data.message)
    }
  })

}
/**
 * 编辑对话框 确定事件
 */
const sureEditorHandler = () => {
  websiteAxios.announcement_update({
    announcementId: editorFormInfo.announcementId,
    announcementTitle: editorFormInfo.announcementTitle,
    announcementDesc: editorFormInfo.announcementDesc,
    announcementContent: editorFormInfo.announcementContent,
    announcementTime: editorFormInfo.announcementTime,
  }).then(res => {
    if (res.data.code == 200) {
      dialogEditorVisible.value = false
      http()
    } else {
      ElMessage.error(res.data.message)
    }
  })
}
/**删除 */
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确定删除么',
      '删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    websiteAxios.announcement_delete({
      announcementId: row.announcementId
    }).then(res => {
      if (res.data.code == 200) {
        ElMessage({
          type: 'success',
          message: "删除成功！！！",
        })
        http()
      } else {
        ElMessage({
          type: 'error',
          message: res.data.message,
        })
      }
    })
  }).catch(error => {
    ElMessage({
      type: 'info',
      message: "取消删除",
    })
  })
}
/**
 * 导入
 */
const onUploadSuccess = (response, uploadFile) => {
  //console.log(response.data)
  websiteAxios.announcement_importByUrl({
    fileUrl: response.data
  }).then(res => {
    if (res.data.code == 200) {
      ElMessage.success("导入成功")
      http()
    } else {
      ElMessage.error(res.data.message)
    }
  })
}
/**
 * 导出
 * @returns {Promise<void>}
 */
const exportHandle = async () => {
  try {
    // 1. **修复URL格式**：去掉多余的斜杠（axios会自动拼接baseURL）
    const response = await axios.get('/back/announcement/export', {
      params: {
        // 2. **强制禁用缓存**：防止浏览器加载旧的空响应
        t: Date.now()
      },
      responseType: 'blob'
    });

    // 3. **核心校验**：检查响应数据是否非空（后端返回空时中断）
    if (response.data.size === 0) {
      ElMessage.error('导出数据为空，请检查题库ID或数据是否存在');
      return;
    }

    // 4. **正确解析文件名**：优先使用后端返回的文件名（处理中文）
    const filename = getFilenameFromHeader(response.headers);

    // 5. **创建带类型的Blob**：明确Excel类型（避免浏览器误判）
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });

    // 6. **安全下载触发**：用户交互事件中执行（避免浏览器拦截）
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename || '公告数据.xlsx'; // 备用文件名
    link.style.display = 'none'; // 防止移动端闪烁

    document.body.appendChild(link);
    link.click(); // 必须在用户点击事件链中调用！

    // 7. **资源清理**：避免内存泄漏
    setTimeout(() => {
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    }, 100);

  } catch (error) {
    // 增强错误提示（区分网络/业务错误）
    if (error.response) {
      ElMessage.error(`服务器错误：${error.response.statusText}`);
    } else {
      ElMessage.error(`网络错误：${error.message}`);
    }
  }
};

// 辅助函数：从响应头解析文件名（处理URLEncoder编码）
const getFilenameFromHeader = (headers) => {
  const disposition = headers['content-disposition'];
  if (!disposition) return null;

  // 匹配filename参数（支持单双引号和无引号）
  const match = disposition.match(/filename\*?=['"]?([^;]+)/i);
  if (match) {
    let filename = decodeURIComponent(match[1].replace(/['"]/g, ''));
    // 处理Spring默认的ISO-8859-1编码回退
    try {
      return decodeURIComponent(filename);
    } catch {
      return filename;
    }
  }
  return null;
};
</script>
<style scoped lang="scss">
.container {
  padding-top: 20px;
  background-size: cover;
}

.header {
  background-color: #ffffff;
  margin-left: 10px;
  margin-right: 10px;
  margin-bottom: 15px;
  padding: 12px;
  border-radius: 10px;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
  display: flex;

  .search {
    width: 100%;

    .input {
      width: 45%;
    }
  }

}

.table-container {
  background-color: #ffffff;
  margin: 10px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);

  .table-header {
    display: flex;

    .button-list {
      color: #ffffff;
      display: flex;
      .button {
        margin-right: 10px;
      }
    }

    .icon-list {
      position: fixed;
      right: 30px;
    }
  }

  .table {
    margin: 10px;
    width: 97%;
  }
}

.bottom {
  position: fixed;
  bottom: 0;
  height: 20px;
  background-color: #ffffff;
  width: 100%;
  padding: 10px;

  span {
    position: fixed;
    right: 20px;
    cursor: pointer;
  }
}

</style>
